package kis.io.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import junit.framework.TestCase;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jdom2.output.LineSeparator;
import org.junit.Test;

public class JdomReadAndWriteXml extends TestCase {

	String path = this.getClass().getResource("/").toString().replace("file:", "") + "TestXml.xml";
	@Test
	public void testWriteXml()
	{
		Element root = new Element("package");
		Document doc = new Document(root);
		Element shop = new Element("shop");
		shop.setAttribute("shopName", "新华书店");
		shop.addContent(new Element("book").setText("java编程思想").setAttribute("id", "1"));
		shop.addContent(new Element("book").setText("HeadFirstJava").setAttribute("id", "2"));
		root.addContent(shop);
		Element shop1 = new Element("shop");
		shop1.addContent(new Element("book").setText("java编程思想").setAttribute("id", "1"));
		root.addContent(shop1);
		Format format = Format.getPrettyFormat();
		format.setEncoding("GBK");// xml头部编码格式
		format.setIndent(null);//不换行。如果不设置为换行
		XMLOutputter putter = new XMLOutputter(format);
		try
		{
			System.out.println(path);
			putter.output(doc, new FileOutputStream(path));
			System.out.println(new FileInputStream(path).available());
		} catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Test
	public void testReadXml() throws Exception{
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(new File(path));
		Element root = doc.getRootElement();//获取package
		List<Element> elmts= root.getChildren();
		for (Element element : elmts)
		{
			System.out.println(element.getAttributeValue("shopName"));
			List<Element> elmts1= element.getChildren();
			for (Element elmt: elmts1)
			{
				System.out.println(elmt.getText());
			}
		}
	}
}
